﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Net.Mail;
using System.Xml;
namespace JobSiteStarterKit.BOL
{
    /// <summary>
    /// Summary description for Common
    /// </summary>
    public class Common
    {
        public Common()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        public static string CreateUserError(MembershipCreateStatus status)
        {
            string msg = "";
            switch (status)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    msg = "Username already exists. Please enter a different user name.";
                    break;
                case MembershipCreateStatus.Success:
                    msg = "Success";
                    break;
                case MembershipCreateStatus.InvalidPassword:
                    msg = "The password provided is invalid. Please enter a valid password value.";
                    break;

                case MembershipCreateStatus.ProviderError:
                    msg = "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
                    break;
                case MembershipCreateStatus.UserRejected:
                    msg = "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
                    break;
                case MembershipCreateStatus.InvalidEmail:
                    msg = "The e-mail address provided is invalid. Please check the value and try again.";
                    break;
                default:
                    msg = "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
                    break;

            }
            return msg;
        }

        public static void Login_Validation(string username, string password, Page objPage, bool IsHomePageLogIn, params bool[] IsAdmin)
        {
            if (Membership.ValidateUser(username, password))
            {
                try
                {
                    using (JobSiteStarterKit.DAL.DBAccess db = new JobSiteStarterKit.DAL.DBAccess())
                    {
                        db.CommandText = "JobsDb_CheckEmailValidatorStatus";
                        System.Data.SqlClient.SqlParameterCollection col = (System.Data.SqlClient.SqlParameterCollection)db.Parameters;
                        System.Data.SqlClient.SqlParameter user_name = new System.Data.SqlClient.SqlParameter("@username", SqlDbType.VarChar, 50);
                        System.Data.SqlClient.SqlParameter user_role = new System.Data.SqlClient.SqlParameter("@userrole", SqlDbType.Int);
                        System.Data.SqlClient.SqlParameter Status = new System.Data.SqlClient.SqlParameter("@Status", SqlDbType.Int);
                        Status.Direction = ParameterDirection.Output;
                        user_name.Value = username;
                        user_role.Direction = ParameterDirection.Output;
                        //user_role.Value = 1; //for company log in 
                        col.AddRange(new System.Data.SqlClient.SqlParameter[] { user_name, user_role, Status });
                        db.ExecuteNonQuery();
                        int iStatus = Convert.ToInt32(Status.Value);
                        if (iStatus == -1)
                        {
                            if (IsHomePageLogIn)
                            {
                                // show error message that your account is not confirmed. plz check ur mail.
                                //and exit from method.
                                string popupScript = "<script language='javascript'>";
                                popupScript += " alert('Sorry! Your account is not confirmed. Please Check your email and confirmed your registration.')";
                                popupScript += "</script>";
                                objPage.RegisterStartupScript("PopupScript", popupScript);
                            }
                            else
                            {
                                Control lbl = objPage.FindControl("lblError");
                                if (lbl != null)
                                {
                                    Label lblError = (Label)lbl;
                                    lblError.Text = "Sorry! Your account is not confirmed. Please Check your email and confirmed your registration.";
                                }

                            }
                            return;

                        }

                    }
                }
                catch (System.Data.SqlClient.SqlException ex)
                {
                    throw ex;
                }

                FormsAuthentication.SetAuthCookie(username, false);


                if (Roles.IsUserInRole(username, System.Web.Configuration.WebConfigurationManager.AppSettings["jobseekerrolename"]))
                {
                    if(IsAdmin.Length < 1)
                        objPage.Response.Redirect("jobseeker/default.aspx");
                    else if(IsAdmin.Length > 0 )
                        objPage.Response.Redirect("../jobseeker/default.aspx");
                }
                else if (Roles.IsUserInRole(username, System.Web.Configuration.WebConfigurationManager.AppSettings["employerrolename"]))
                {
                    if(IsAdmin.Length<1)
                        objPage.Response.Redirect("employer/default.aspx");
                    else if(IsAdmin.Length >0 )
                        objPage.Response.Redirect("../employer/default.aspx");
                }

            }
            else
            {
                if (IsHomePageLogIn)
                {
                    string popupScript = "<script language='javascript'>";
                    popupScript += " alert('Sorry! Your Username  or Password may invalid.Please try again.')";
                    popupScript += "</script>";
                    objPage.RegisterStartupScript("PopupScript", popupScript);
                }
                else
                {
                    Label lbl = (Label)objPage.FindControl("lblError");
                    if (lbl != null)
                    {
                        //Label lblError = (Label)lbl;
                        lbl.Text = "Sorry! Your Username  or Password may invalid.Please try again.";
                    }

                }
            }
        }

        public static void JobseekarLogin(string username, string password, Page objPage, bool IsHomePageLogIn, params bool[] IsAdmin)
        {
            JobSiteStarterKit.DAL.DBAccess db = new JobSiteStarterKit.DAL.DBAccess();
            db.AddParameter("@JobSeekerEmail", username);
            db.AddParameter("@JobSeekerUserName", password);
            DataSet ds = new DataSet();
            ds = db.ExecuteDataSet("proc_Jobseekar_Login");
            if (ds != null)
            {
                if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                   // FormsAuthentication.SetAuthCookie(username, false);              
                    objPage.Session["SESS_JobSeekerUserName"] = ds.Tables[0].Rows[0]["JobSeekerUserName"].ToString().Trim();
                    objPage.Session["SESS_JobSeekerName"] = ds.Tables[0].Rows[0]["JobSeekerName"].ToString().Trim();
                    objPage.Response.Redirect("./jobseeker/default.aspx");
                }

            }
            else
            {
                string popupScript = "<script language='javascript'>";
                popupScript += " alert('Sorry! Your Username  or Password may invalid.Please try again.')";
                popupScript += "</script>";
                objPage.RegisterStartupScript("PopupScript", popupScript);
            }
            
        }
        public static void SendEmail(string emailAddress, string Subject, string Message)
        {
            string mailserver = System.Web.Configuration.WebConfigurationManager.AppSettings["smtpserver"];
            string mailaddress = System.Web.Configuration.WebConfigurationManager.AppSettings["webmasteremail"];
            string mailuserpwd = System.Web.Configuration.WebConfigurationManager.AppSettings["webmasteremailpwd"];

            try
            {

                string strBody = Message;

                string strDefualtUserName = mailaddress;
                string strDefaultPassword = mailuserpwd;
                string strSmtpServer = mailserver;
                string strEmailAddress = emailAddress;

                MailMessage message = new MailMessage();
                MailAddress fromMail = new MailAddress(mailaddress);
                message.IsBodyHtml = true;
                message.From = fromMail;
                message.To.Add(emailAddress);
                message.Subject = Subject;
                message.IsBodyHtml = true;
                message.Body = strBody;
                SmtpClient emailClient = new SmtpClient(strSmtpServer);
                System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(strDefualtUserName, strDefaultPassword);
                emailClient.UseDefaultCredentials = false;
                emailClient.Credentials = SMTPUserInfo;
                emailClient.Send(message);
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        public static void SendEMAILVerificationMail(string emailAddress, string username, string userrole)
        {
            string mailserver = System.Web.Configuration.WebConfigurationManager.AppSettings["smtpserver"];
            string mailaddress = System.Web.Configuration.WebConfigurationManager.AppSettings["webmasteremail"];
            string mailuserpwd = System.Web.Configuration.WebConfigurationManager.AppSettings["webmasteremailpwd"];
            try
            {
                string userid = "";
                try
                {
                    using (JobSiteStarterKit.DAL.DBAccess db = new JobSiteStarterKit.DAL.DBAccess())
                    {
                        db.CommandText = "JobsDb_GetUserIdByName";
                        System.Data.SqlClient.SqlParameterCollection col = (System.Data.SqlClient.SqlParameterCollection)db.Parameters;
                        System.Data.SqlClient.SqlParameter user_name = new System.Data.SqlClient.SqlParameter("@username", SqlDbType.VarChar, 50);
                        System.Data.SqlClient.SqlParameter user_id = new System.Data.SqlClient.SqlParameter("@userid", SqlDbType.VarChar, 500);
                        user_id.Direction = ParameterDirection.Output;
                        user_name.Value = username;
                        col.AddRange(new System.Data.SqlClient.SqlParameter[] { user_name, user_id });
                        db.ExecuteNonQuery();
                        userid = Convert.ToString(user_id.Value);
                    }
                }
                catch (System.Data.SqlClient.SqlException SqlEx)
                {
                    throw SqlEx;
                }
                string strBody = "";
                strBody = "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>";
                strBody += "<html xmlns='http://www.w3.org/1999/xhtml'>";
                strBody += " <head>";
                strBody += " <meta content='text/html; charset=utf-8' http-equiv='Content-Type' />";
                strBody += " <title>Account verification</title>";
                strBody += " <style type='text/css'>";
                strBody += ".style1 {";
                strBody += "	text-decoration: underline;";
                strBody += " }";
                strBody += ".style2 {";
                strBody += "	font-family: Arial, Helvetica, sans-serif;";
                strBody += " }";
                strBody += ".style3 {";
                strBody += "font-size: small;";
                strBody += " }";
                strBody += " </style>";
                strBody += " </head>";

                strBody += " <body>";

                strBody += " <p><strong>Hello, <span class='style1'>" + username + "</span></strong></p>";
                strBody += " <span class='style2'><span class='style3'>You recently created a new ";
                strBody += " account to our </span><a href='http://www.z2plus.com'><span class='style3'>";
                strBody += " www.rozgarstreet.com</span></a><span class='style3'> employer services, or initiated verification of an existing email address. To verify that you own this email address, simply click on the link below.	 ";
                strBody += "	Verifying your email address ensures that you can securely retrieve your account information if your password is lost or stolen. You must verify your email address before you can use it on  ";
                strBody += " www.rozgarstreet.com services that require an email address.	 ";
                strBody += " 	For your security, please keep your email address information up to date. If this information changes, you can always update it by signing in to your ";
                strBody += " www.rozgarstreet.com! account and changing it from the 'My Profile' area.<br />	 ";
                strBody += " Verify '" + emailAddress + "' ";
                strBody += " If you can't click the link above, you can verify your email address by cutting and pasting (or typing) the following address into your browser:</span></span><span class='style3'><br />";
                strBody += " &nbsp;http://www.rozgarstreet.com/verify.aspx?identify=" + userid + "&role=" + userrole;
                strBody += " </span>";
                strBody += "<br />";
                if (userrole == "2")
                {
                    strBody += "<strong style='color:red;'>Note: </strong>";
                    strBody += "Your account is valid for 30 days. Please contact below for further information.<br />";
                    strBody += "<strong>Email Address : </strong><span class='style3'>rozgarstreet@gmail.com</span><br />";
                    strBody += "<strong>Contact Number: </strong><span class='style3'>05422280083, +918874888812</span><br />";
                    strBody += "<strong>Mobile Number: </strong><span class='style3'>+918874888812</span><br />";


                }
                strBody += "<strong>With regards, </strong><br />";
                strBody += "<strong>RozgarStreet Placement & Security Services </strong><br />";

                strBody += "<span class='style3'>S2/284,Bhojubir</span><br />";
                strBody += "<span class='style3'>Varanasi - 221003</span><br />";
                strBody += "<strong>For more details click on </strong><a href='http://www.rozgarstreet.com/contactrozgarstreet.aspx'></a><br />";

                strBody += " </body> ";
                strBody += "</html>";

                string strDefualtUserName = mailaddress;
                string strDefaultPassword = mailuserpwd;
                string strSmtpServer = mailserver;
                string strEmailAddress = emailAddress;

                MailMessage message = new MailMessage();
                MailAddress fromMail = new MailAddress(mailaddress);
                message.IsBodyHtml = true;
                message.From = fromMail;
                message.To.Add(emailAddress);
                message.Subject = "Thanks for registration in www.rozgarstreet.com";
                message.IsBodyHtml = true;
                message.Body = strBody;
                SmtpClient emailClient = new SmtpClient(strSmtpServer);
                System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(strDefualtUserName, strDefaultPassword);
                emailClient.UseDefaultCredentials = false;
                emailClient.Credentials = SMTPUserInfo;
                emailClient.Send(message);
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        public static string ReadCommonSettingsAttributes(string key,HttpContext con)
        {
        String strValue= "";
        String ConfigFilePath= con.Server.MapPath("../App_Data/Adminpass.xml");
       System.Xml.XmlDocument file=new System.Xml.XmlDocument();
            
        XmlTextReader m_xmlr;
        //Create the XML Reader

        m_xmlr = new XmlTextReader(ConfigFilePath);
        //Disable whitespace so that you don't have to read over whitespaces

        m_xmlr.WhitespaceHandling = WhitespaceHandling.None;
        //read the xml declaration and advance to family tag

        m_xmlr.Read();
        //read the family tag

        m_xmlr.Read();
       //Load the Loop

        while (!m_xmlr.EOF)
            //Go to the name tag
            {
            m_xmlr.Read();
            //if not start element exit while loop

          
           
            //Get the Gender Attribute Value

           string popservernameAttribute= m_xmlr.GetAttribute("key");
            if (popservernameAttribute == key)

                {
                strValue = m_xmlr.GetAttribute("value");
                m_xmlr.Close();
                   return strValue;
                  
                }
               
            //Read elements firstname and lastname

            //m_xmlr.Read()
            //Get the firstName Element Value

            //Dim firstNameValue = m_xmlr.ReadElementString("firstname")
            //Get the lastName Element Value

            //Dim lastNameValue = m_xmlr.ReadElementString("lastname")
           //Write Result to the Console

            //'Console.WriteLine("Gender: " & genderAttribute _
            //'  & " FirstName: " & firstNameValue & " LastName: " _
            //'  & lastNameValue)
            //'Console.Write(vbCrLf)
            }
        //close the reader

        m_xmlr.Close();

        return strValue;
        }

        public static void WriteCommonSettingsAttributes(string pwd, HttpContext con)
        {
            String strValue = "";
            string struname=ReadCommonSettingsAttributes("AdminUserName",con);
            String ConfigFilePath = con.Server.MapPath("../App_Data/Adminpass.xml");
            System.Xml.XmlDocument file = new System.Xml.XmlDocument();

            XmlTextWriter m_xmlr;
            //Create the XML Reader

            m_xmlr = new XmlTextWriter(ConfigFilePath,null );
            //Disable whitespace so that you don't have to read over whitespaces
            m_xmlr.WriteStartDocument();
            m_xmlr.Formatting = Formatting.Indented;
            m_xmlr.WriteStartElement("settings");
            m_xmlr.WriteStartElement("add");
            m_xmlr.WriteAttributeString("key", "AdminUserName");
            m_xmlr.WriteAttributeString("value", struname);
            m_xmlr.WriteEndElement();


            m_xmlr.WriteStartElement("add");
            m_xmlr.WriteAttributeString("key", "AdminPwd");
            m_xmlr.WriteAttributeString("value", pwd);
            m_xmlr.WriteEndElement();

            m_xmlr.Close();
           
        }

        public static void sendemail(string emailAddress, string subject, string msg)
        {
            string mailserver = System.Web.Configuration.WebConfigurationManager.AppSettings["smtpserver"];
            string mailaddress = System.Web.Configuration.WebConfigurationManager.AppSettings["webmasteremail"];
            string mailuserpwd = System.Web.Configuration.WebConfigurationManager.AppSettings["webmasteremailpwd"];



            MailMessage message = new MailMessage();
            MailAddress fromMail = new MailAddress(mailaddress);
            message.IsBodyHtml = true;
            message.From = fromMail;
            message.To.Add(emailAddress);
            message.Subject = subject;
            message.IsBodyHtml = true;
            message.Body = msg;
            SmtpClient emailClient = new SmtpClient(mailserver);
            System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(mailaddress, mailuserpwd);
            emailClient.UseDefaultCredentials = false;
            emailClient.Credentials = SMTPUserInfo;
            emailClient.Send(message);
        }

       
    }
     

}